app.directive('compareTo', [
    '$timeout',
    function($timeout) {
        return {
            require: 'ngModel',
            scope: {
                otherModelValue: '=compareTo'
            },
            link: function(scope, element, attributes, ngModel) {
                ngModel.$validators.compareTo = function(modelValue) {
                    return modelValue == scope.otherModelValue;
                };
                scope.$watch('otherModelValue', function() {
                    ngModel.$validate();
                });
            }
        };
    }
]);

app.directive('previewPicture', ['$sce', function($sce) {
    return {
        scope: {
            datas: '=datas'
        },
        template: "<ol class='preview_picture'>"
                +"    <li ng-repeat='(key, arr) in arrs track by key'>"
                +"        <h4>{{arr.title}}</h4>"
                +"        <ul class='list'>"
                +"           <li class='yf-shadow' ng-repeat='(kp, pic) in arr.data_group track by kp' ng-click='downloadPdf(pic.image.url);'>"
                +"                <img ng-src='{{ pic.image.url | to_url }}'' data-action='zoom'>"
                +"                <h4>{{ pic.serial_number }}</h4>"
                +"            </li>"
                +"        </ul>"
                +"    </li>"
                +"</ol>",
        link: function(scope, element, attributes) {

            function getObj(data) {
                var obj = {
                    title: data.title,
                    brand_id: data.brand_id,
                    data_group: []
                };
                obj.data_group.push(data);
                return obj;
            }

            function arrFn(datas) {
                var id_arrs = [];
                datas.forEach(function(v, k) {
                    var idx = id_arrs.indexOf(v.brand_id);
                    if(idx == -1) {
                        id_arrs.push(v.brand_id);
                        scope.arrs.push(getObj(v));
                    } else {
                        scope.arrs[idx].data_group.push(v);
                    }
                });
            }

            scope.$watch('datas', function(newData, oldData) {
                if(newData) {
                    scope.arrs = [];
                    arrFn(newData)
                }
            });

            scope.downloadPdf = function(url) {
                var split_url = url.slice(-3);
                if (['pdf', 'dwg'].indexOf(split_url) != -1) {
                    window.open($sce.trustAsUrl(url), '_blank');
                }
            };
        }
    }
}]);

app.directive('orderLabel', [function() {
        return {
            scope: {
                mount_order: '=state'
            },
            template: "<div class='orderlabel yf-shadow' ng-class=\"{'install': mount_order}\" ng-bind='mount_order ? \"安装单\": \"测量单\"'></div>"
        };
    }
]);

app.directive('journal', [
    '$sce',
    function($sce) {
        // var template = '<div class="panel panel-default order-records">'
        //                 +    '<div class="panel-heading yf-shadow">'
        //                 +        '<h4>订单日志</h4>'
        //                 +    '</div>'
        //                 +    '<div class="panel-body">'
        //                 +        '<ul class="list-group">'
        //                 +            '<li class="list-group-item yf-shadow" ng-repeat="(key, e) in order_events | limitTo: limit track by key" ng-class="{ \'hover\': (e.event == \'installation\' && order.measure_pictures.length > 0 ) || (e.event == \'installed\' && order.completed_pictures.length > 0) }" ng-click="openEvent(e.event);">'
        //                 +                '<div class="row">'
        //                 +                    '<div class="col-md-10 col-sm-10 col-xs-10 order-record-info">'
        //                 +                        '{{ e.title }}'
        //                 +                        '<p>{{ e.updated_at * 1000 | date: "yyyy-MM-dd HH:mm"}}</p>'
        //                 +                    '</div>'
        //                 +                   '<div class="col-md-2 col-sm-2 col-xs-2 text-center order-record-btn" ng-if="(e.event == \'installation\' && order.measure_pictures.length > 0 && !isshowmeasured) || (e.event == \'installed\' && order.completed_pictures.length > 0 && !isappointed_installation)">'
        //                 +                        '<a class="pull-right">+</a>'
        //                 +                    '</div>'
        //                 +                '</div>'
        //                 +                '<ol class="" ng-show="e.event == \'installation\' && isshowmeasured && order.measure_pictures && order.measure_pictures.length > 0">'
        //                 +                    '<li ng-repeat="(key, data_pics) in order.measure_pictures track by key" ng-click="downloadPdf(pic.image.url);">'
        //                 +                        '<div>{{data_pics[0].updated_at * 1000 | date: "yyyy-MM-dd HH:mm"}} 上传的测量图片</div>'
        //                 +                        '<ul class="previewhostroy">'
        //                 +                           '<li ng-repeat="(index, pic) in data_pics track by index">'
        //                 +                               '<img ng-src="{{ pic.image.url | to_url }}" data-action="zoom">'
        //                 +                           '</li>'
        //                 +                        '</ul>'
        //                 +                    '</li>'
        //                 +                '</ol>'
        //                 +                '<ul class="previewhostroy" ng-show="e.event == \'installed\' && isappointed_installation && order.completed_pictures && order.completed_pictures.length > 0">'
        //                 +                    '<li ng-repeat="(key, pic) in order.completed_pictures track by key" ng-click="downloadPdf(pic.image.url);">'
        //                 +                        '<img ng-src="{{ pic.image.url | to_url }}" data-action="zoom">'
        //                 +                    '</li>'
        //                 +                '</ul>'
        //                 +            '</li>'
        //                 +        '</ul>'
        //                 +            '<nav ng-show="order.order_events.length != 0 && page.total_count > limit">'
        //                 +                '<ul class="pager pager-sm yf-pager">'
        //                 +                    '<li>'
        //                 +                        '<a class="btn btn-default" ng-disabled="!((page.current_page - 1) >= 1)" ng-click="setPage(page.current_page - 1);">上一页</a>'
        //                 +                    '</li>'
        //                 +                    '<li>'
        //                 +                        '<a class="btn btn-default" ng-disabled="!((page.total_pages - page.current_page) > 0)" ng-click="setPage(page.current_page + 1);">下一页</a>'
        //                 +                    '</li>'
        //                 +                '</ul>'
        //                 +            '</nav>'
        //                 +    '</div>'
        //                 +'</div>';
        var template = '<div class="panel yf-shadow">' +
        '<div class="panel-heading">' +
        '<h4>订单日志</h4>' +
        '</div>' +
        '<div class="panel-body">' +
        '<ul class="list-group">' +
        '<li class="list-group-item" ng-repeat="(key, e) in order_events | limitTo: limit track by key" ng-class="{ \'hover\': (e.event == \'installation\' && order.measure_pictures.length > 0 ) || (e.event == \'installed\' && order.completed_pictures.length > 0) }" ng-click="openEvent(e.event);">' +
        '<div class="row">' +
        '<div class="col-md-10 col-sm-10 col-xs-12 order-record-info">' +
        '{{ e.title }}' +
        '<p>{{ e.updated_at * 1000 | date: "yyyy-MM-dd HH:mm"}}</p>' +
        '</div>' +
        '<div class="col-md-2 col-sm-2 col-xs-2 text-center order-record-btn" ng-if="(e.event == \'installation\' && order.measure_pictures.length > 0 && !isshowmeasured) || (e.event == \'installed\' && order.completed_pictures.length > 0 && !isappointed_installation)">' +
        '<a class="pull-right">+</a>' +
        '</div>' +
        '</div>' +
        '<ol class="" ng-show="e.event == \'installation\' && isshowmeasured && order.measure_pictures && order.measure_pictures.length > 0">' +
        '<li ng-repeat="(key, data_pics) in order.measure_pictures track by key">' +
        '<div>{{data_pics[0].updated_at * 1000 | date: "yyyy-MM-dd HH:mm"}} 上传的测量图片</div>' +
        '<ul class="previewhostroy preview_img">' +
        '<li class="yf-shadow" ng-repeat="(index, pic) in data_pics | orderBy: \'brand_id\' track by index" ng-click="downloadPdfAndDwg(pic.image.url);">' +
        '<h4 class="title">{{ pic.title }}</h4>'+
        '<img ng-src="{{ pic.image.url | to_url }}" data-action="zoom">' +
        '<h4>{{ pic.serial_number }}</h4>'+
        '</li>' +
        '</ul>' +
        '</li>' +
        '</ol>' +
        '<ul class="previewhostroy preview_img" ng-show="e.event == \'installed\' && isappointed_installation && order.completed_pictures && order.completed_pictures.length > 0">' +
        '<li class="yf-shadow" ng-repeat="(key, pic) in order.completed_pictures | orderBy: \'brand_id\' track by key" ng-click="downloadPdfAndDwg(pic.image.url);">' +
        '<h4 class="title">{{ pic.title }}</h4>'+
        '<img ng-src="{{ pic.image.url | to_url }}" data-action="zoom">' +
        '<h4>{{ pic.serial_number }}</h4>'+
        '</li>' +
        '</ul>' +
        '</li>' +
        '</ul>' +
        '<nav ng-show="order.order_events.length != 0 && page.total_count > limit">' +
        '<ul class="pager pager-sm yf-pager">' +
        '<li>' +
        '<a class="btn btn-default" ng-disabled="!((page.current_page - 1) >= 1)" ng-click="setPage(page.current_page - 1);">上一页</a>' +
        '</li>' +
        '<li>' +
        '<a class="btn btn-default" ng-disabled="!((page.total_pages - page.current_page) > 0)" ng-click="setPage(page.current_page + 1);">下一页</a>' +
        '</li>' +
        '</ul>' +
        '</nav>' +
        '</div>' +
        '</div>';
        return {
            scope: {
                order: '=order'
            },
            template: template,
            link: function($scope, $element, $attributes) {
                $scope.limit = limit;
                var events = [];
                $scope.$watch('order', function(newdata) {
                    if (newdata) {
                        $scope.order_events = events = angular.copy($scope.order.order_events);
                        var events_len = events.length
                        $scope.page = {
                            current_page: 1,
                            total_count: events_len || 0,
                            pagesLength: limit,
                            total_pages: Math.ceil(events_len / limit)
                        };
                    }
                });

                $scope.setPage = function(page) {
                    if (page > 0 && page <= $scope.page.total_pages) {
                        $scope.page.current_page = page;
                        page = (page - 1) * limit;
                        $scope.order_events = events.slice(page, page + limit)
                    }
                };

                $scope.isshowmeasured = false;
                $scope.isappointed_installation = false;
                $scope.openEvent = function(e) {
                    if (e == 'installation') {
                        $scope.isshowmeasured = true;
                    } else if (e == 'installed') {
                        $scope.isappointed_installation = true;
                    }
                };

                $scope.downloadPdfAndDwg = function(url) {
                    // console.log('url', url)
                    var split_url = url.slice(-3);
                    if (['pdf', 'dwg'].indexOf(split_url) != -1) {
                        window.open($sce.trustAsUrl(url), '_blank');
                    }
                };
            }
        };
    }
]);

app.directive('ngEnter', [function() {
        return function(scope, element, attrs) {
            element.bind('keydown keypress', function(event) {
                if (event.keyCode === 13) {
                    scope.$apply(function() {
                        scope.$eval(attrs.ngEnter);
                    });
                    event.preventDefault();
                }
            });
        };
    }
]);

app.directive('star', [function() {
        var starhtml = '<i class="icon-xing c1"></i>';
        return {
            scope: {
                len: '=len'
            },
            template: '<span ng-bind-html="template | to_trusted"></span>',
            link: function($scope, $element, $attributes) {

                $scope.$watch('len', function(newdata, olddata) {
                    $scope.template = '';
                    if (newdata) {
                        var num = Math.round($scope.len);
                        if(num >= 5) {
                            num = 5;
                        }
                        for (var i = 0; i < num; i++) {
                            $scope.template += starhtml;
                        }
                    }
                });

            }
        };
    }
]);

app.directive('setTime', [
    '$filter',
    function($filter) {
        return {
            scope: {
                time: '=time'
            },
            link: function(scope, element, attr, ngModel) {
                scope.$watch('time', function(newdata, olddata) {
                    if (newdata) {
                        newdata *= 1000;
                        var time = $filter('date')(newdata, "yyyy-MM-dd HH:mm");
                        var attrid = "#" + attr.id;
                        // $( attrid ).val(time);
                        $(function() {
                            // $( attrid ).val(time);
                            $(attrid).attr('value', time);
                        });
                    }
                });
            }
        };
    }
]);

app.directive('empty', [
    '$timeout',
    function($timeout) {
        return {
            scope: {
                data: '=data',
                text: '=text'
            },
            template: '<section class="empty-content" ng-show="isempty">{{ empty_text }}</section>',
            link: function(scope, element, attr) {
                scope.isempty = false;
                scope.empty_text = '暂无内容';
                if(scope.text) { scope.empty_text = scope.text }
                scope.$watch('data', function(newdata, olddata) {
                    // console.log('newdata, olddata', newdata, olddata);
                    if (!newdata || newdata.length == 0) {
                        // $timeout(function() {
                        //     scope.isempty = true;
                        // }, 1000);
                        scope.isempty = true;
                    } else {
                        scope.isempty = false;
                    }
                });
            }
        };
    }
]);

app.directive('inputFormat', [function() {
        return {
            require: '?ngModel',
            link: function(scope, element, attr, ngModel) {
                var len;
                if (!ngModel) {
                    return;
                }
                len = 10;
                scope.$watch(function() {
                    return ngModel.$viewValue;
                }, function(value) {
                    if (value) {
                        ngModel.$setViewValue(value.replace(/[^\d.]/g, '').substr(0, len));
                        ngModel.$render();
                    }
                });
            }
        };
    }
]);

app.directive('downFile', [
    '$http',
    function($http) {
        return {
            restrict: 'A',
            scope: {
                params: '=searchData'
            },
            link: function(scope, element, attr) {
                var ele = $(element);
                ele.on('click', function(e) {
                    ele.prop('disabled', true);
                    e.preventDefault();
                    var params = null;
//                  var paramsObj=null;
//                  paramsObj=angular.copy(scope.params.limit);
					url=angular.copy(scope.params.url);
					delete scope.params.url;
					console.log(scope.params,url);
//					if(scope.params.limit>30){
//						paramsObj.page=1;
//						for(var i=30;i<=scope.params.limit;i++){
//							i=i+29;
//							paramsObj.page++;
//							paramsObj=i;
//							console.log(paramsObj);
//							httpServe();
//						}
//					}else{
//						httpServe();
//					}
//					console.log(paramsObj);
//					function httpServe(){
						$http({
	                        url: api + url + '.xlsx',
	                        method: 'get',
	                        responseType: 'arraybuffer',
	                        'Content-Type': 'application/xlsx',
	                        Authorization: attr.nowToken,
	                        params: scope.params
	                    }).success(function(data, status, headers) {
	                    		console.log(data);
	                        ele.prop('disabled', false);
	                        var type;
	                        switch (attr.downFileType) {
	                            case 'xlsx':
	                                type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
	                                break;
	                        }
	                        if (!type)
	                            throw '无效类型';
	                        var url = URL.createObjectURL(new Blob([data], {type: type}));
	                        var a = document.createElement('a');
	                        a.href = url;
	                        a.download = '导出.xlsx';
	                        a.target = '_blank';
	                        a.click();
	                        // saveAs(new Blob([data], { type: type }), decodeURI(headers()["x-filename"]));  // 中文乱码
	                    }).error(function(data, status) {
	                        ele.prop('disabled', false);
	                    });
//					}
                    
                });
            }
        };
    }
]);

// app.directive('mutiUploadImages', [
//     '$http',
//     '$timeout',
//     function($http, $timeout) {
//         var template = [
//             '<div class="row margin-reset mutiUploadImagePanel" ng-repeat="imageArr in imageArrs">',
//                 '<div class="panel">',
//                     '<div class="panel-body">',
//                         '<div class="row margin-reset">',
//                             '<div class="col-sm-2 col-sm-6">',
//                               // '<select class="form-control" id="" ng-model="imageArr.brand_id" ng-options="brand.id as brand.name for brand in brands.company" required>',
//                               //     '<option value="" selected>请选择品牌</option>',
//                               // '</select>',
//                             '</div>',
//                             '<div class="col-sm-7 col-sm-8 img_file">',
//                               '<div ng-repeat="count in mutiCount">',
//                                 '<input type="file" name="images{{imageArr.id}}{{count}}" id="images{{imageArr.id}}{{count}}" style="display: none;">',
//                                 '<img class="uploadImageBtn" style="margin: 5px;" data-id="images{{imageArr.id}}{{count}}" src="./components/mine/orders/imgs/addpic.png">',
//                               '</div>',
//
//                             '</div>',
//                         '</div>',
//                     '</div>',
//                 '</div>',
//             '</div>'
//         ].join('')
//         return {
//             template: template,
//             link: function($scope, $element, $attributes) {
//                 $scope.mutiCount = [];
//                 for(var i= 0; i < $attributes.mutiCount; i++ ){
//                   $scope.mutiCount.push(i);
//                 }
//                 $scope.imageArrs = [
//                     {
//                         id: 0,
//                         brand_id: null,
//                     }
//                 ]
//
//                 $(document).ready(function() {
//                   $('.img_file').find('img').on('click', function(res){
//                       var id = '#' + $(this).data('id');
//                       console.log(id, res)
//                       // $timeout(function() {
//                         console.log('$(id)', $(id))
//                         $(id).on('click', function(e){
//                           console.log('ss', e)
//                         }, function(asdf) {
//                           console.log('asdf', asdf)
//                         });
//                       // }, 500)
//                   });
//                 })
//             }
//         }
//     }
// ]);
